package com.xxy.controller;

import cn.hutool.core.util.StrUtil;
import com.xxy.common.Result;
import com.xxy.mapper.UserMapper;
import com.xxy.pojo.User;
import com.xxy.pojo.dto.mytestRequest;
import com.xxy.services.UserService;
import com.xxy.utils.JwtUtil;
import com.xxy.utils.Md5Util;
import com.xxy.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author xingyu Xue
 * @Date 2024/1/26 9:01
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Validated
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;

    /**
     * 注册接口
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$")String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        log.info("register~~~~");
        //查询用户名
        User byUserName = userService.findByUserName(username);
        log.info("查询到的用户信息：{}",byUserName);
        if (byUserName ==null){
            log.info("用户名没有被占用,开始注册~~~~");
            //没有被占用，开始注册
            userService.register(username,password);


            return Result.success("注册成功");
        }else {
            return Result.error("用户名已经被占用");

        }

    }

    /**
     * 登录接口 登录成功后，保存用户id和username信息到token中，并返回给前端
     * @param username 用户名
     * @param password 用户密码
     * @return token
     */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        if (username == null || password == null){
            return Result.error("账号密码不能为空");
        }

        User loginUser = userMapper.findByUserName(username);
        //判断用户是否存在
        if (loginUser == null){
            return Result.error("用户名错误");
        }

        //判断密码是否正确  loginUser对象中的password是密文
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            //登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);


            return Result.success(token);
        }

        //密码不正确
        return Result.error("密码错误");
    }

    @PostMapping("/mytest")
    public Result mytest(@RequestParam String name ){
//        System.out.println(a.getName());
//        System.out.println(a.getAge());
        System.out.println(name);
        return  Result.success();
    }

    /**
     * 该接口用于获取当前已登录用户的详细信息
     * @return
     */
    @GetMapping("/userinfo")
    public Result<User> getUserInfo(/*HttpServletRequest request*/){
        //从threadlocal中获取用户信息
        Map<String, Object> res = ThreadLocalUtil.get();
//        String token = request.getHeader("Authorization");
//        Map<String, Object> res = JwtUtil.parseToken(token);
        Integer id = (Integer) res.get("id");
        log.info("用户id:{}",id);
        User resultUser = userService.getById(id);

        return Result.success(resultUser);
    }

    /**
     * 该接口用于更新已登录用户的基本信息(除头像和密码)
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);

        return Result.success();

    }

    /**
     * 该接口用于更新已登录用户的头像
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params ){
        //1.校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (StringUtils.isAllEmpty(oldPwd,newPwd,rePwd))  return Result.error("缺少参数");

        //2、判断用户是否存在 原密码输入是否正确，
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User byUserName = userService.findByUserName(username);
        if (byUserName == null){
            return Result.error("用户不存在");
        }
        if (!Md5Util.getMD5String(oldPwd).equals(byUserName.getPassword())){
            return Result.error("原密码不正确");
        }

        //3、新密码和确认密码是否相同
        if (!rePwd.equals(newPwd)){
            return Result.error("两次填写的新密码不一样");
        }
        //4.调用service完成密码更新
        userService.updatePwd(newPwd);


        return Result.success();
    }

}
